package rejjie.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import rejjie.common.BaseContext;
import rejjie.common.R;
import rejjie.entity.Employee;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.Enumeration;

@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获得本次请求的url
        String url = request.getRequestURI();
        log.info("本次登录的url是"+url);

        //2.判断本次请求的是否需要处理

        // 这里定义的是不需要处理的url
        String[] urls= new String[]{
          "/employee/login",
          "/employee/logout",
          "/backend/**",
          "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/user/loginout"

        };

        boolean check = check(urls, url);
        //3.如果不需要处理，直接放行
        if(check){
            log.info("不需要处理，直接放行"+url);
            // 直接放行
            filterChain.doFilter(request,response);
            return;
        }

        //4.判断登录状态，如果已经登录直接放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已经登录");
            Long empID = (Long)request.getSession().getAttribute("employee");
            log.info("",empID);
            BaseContext.setCurrentID(empID);
            filterChain.doFilter(request,response);
            return;
        }

        //4.判断登录状态，如果已经登录直接放行
        if(request.getSession().getAttribute("user")!=null){
            log.info("前端用户已经登录");
            Long UserID = (Long)request.getSession().getAttribute("user");
            log.info("",UserID);
            BaseContext.setCurrentID(UserID);
            filterChain.doFilter(request,response);
            return;
        }


        //5.如果未登录返回未登录结果
        log.info("用户没用登录");
        // 因为方法没有返回值，所以通过流的方式，把东西写入json,前端会有拦截器进行拦截
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 进行路径匹配
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url:urls) {
            if(PATH_MATCHER.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
